package yxy.game.pm2.command.office;

import yxy.cherry.data.DataCenter;
import yxy.cherry.data.bean.herodata;
import yxy.cherry.game.base.message.MessageEmitterHandler;
import yxy.cherry.game.base.message.annotation.MessageSource;
import yxy.cherry.game.base.message.annotation.MessageType;
import yxy.game.pm2.Result;
import yxy.game.pm2.bean.Hero;
import yxy.game.pm2.command.Command;
import yxy.game.pm2.message.OfficeMessage;
import yxy.game.pm2.module.hero.HeroHandle;
import yxy.game.pm2.module.office.OfficeModule;

/** 主公府 主公府武将置换确认 */
@MessageType(proto = Command.OfficeHeroChangeConfirm, classtype = OfficeMessage.OfficeHeroChangeConfirmRequest.class)
public class CMD_OfficeHeroChangeConfirm extends Command<OfficeMessage.OfficeHeroChangeConfirmRequest> {

	@Override
	public void execute(MessageSource messageSource, OfficeMessage.OfficeHeroChangeConfirmRequest request) {
		String playerCode = messageSource.getTag();
		boolean confirm = request.getConfirm();

		OfficeMessage.OfficeHeroChangeConfirmResponse.Builder response = OfficeMessage.OfficeHeroChangeConfirmResponse.newBuilder();

		OfficeModule officeModule = OfficeModule.get(playerCode);
		if (officeModule == null) {
			send(messageSource, response, Result.ModuleNotOpen);// 模块未开启
			return;
		}

		try {
			if (Hero.lockHero(playerCode) && officeModule.tryLock()) {

				if (confirm) {
					if (officeModule.getChangeHeroCode() == null || officeModule.getTargetHeroId() == 0) {
						send(messageSource, response, Result.ParamError);// 请先操作置换
						return;
					}

					HeroHandle heroHandle = new HeroHandle();
					Hero hero = heroHandle.getHero(playerCode, officeModule.getChangeHeroCode());
					herodata data = DataCenter.getData(officeModule.getTargetHeroId(), herodata.class);
					if (hero == null || data == null || hero.getStar() < 4 || hero.getStar() > 5) {
						send(messageSource, response, Result.ParamError);
						return;
					}
					hero.setDataId(data.getId());
					heroHandle.updateHero(playerCode, hero);

					response.setChange(heroHandle.getHeroSimple(playerCode, hero));
				}

				officeModule.setChangeHeroCode(null);
				officeModule.setTargetHeroId(0);
				officeModule.set();

				send(messageSource, response, Result.Success);
			}
		} catch (Exception e) {
			e.printStackTrace();
			send(messageSource, response, Result.DataError);
		} finally {
			officeModule.unlock();
			Hero.unlockHero(playerCode);
		}
	}

	private void send(MessageSource messageSource, OfficeMessage.OfficeHeroChangeConfirmResponse.Builder response, Result result) {
		response.setResult(result.packResult());
		MessageEmitterHandler.getInstance().send(messageSource, response.build());
	}
}